﻿/*****************************************************
 * DocumentManager                                   *
 * Made by Niklas Plüm (l4nm4n@users.sourceforge.net)*
 *****************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using VisualPureBasicIDE.CoreGUI.Exceptions;
using WeifenLuo.WinFormsUI.Docking;

namespace VisualPureBasicIDE.CoreGUI
{
    public static class DocumentManager
    {
        private static Dictionary<string, Document> _documentsDictionary;
        private static int _newDocumentCounter;

        /// <summary>
        /// Creates a new PureBasic source file
        /// </summary>
        public static void NewSourceFile()
        {
            retry:
            try
            {
                var doc = new Document(Translator.GetStringAndTranslate("strNewDocument") + ' ' + _newDocumentCounter++)
                              {
                                  Text = Translator.GetStringAndTranslate("strEnterYourSourceHere")
                              };

                // TODO: Implement a TemplateManager and link it with the DocumentManager
                AddDocument(doc, ApplicationManager.MainForm.DockPanel);
            }
            catch (Exception ex)
            {
                if (
                    MessageBox.Show(
                        ex.Message,
                        Translator.GetStringAndTranslate("strError"), MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Retry)
                    goto retry;
            }
        }

        /// <summary>
        /// Opens an existing PureBasic source file
        /// </summary>
        public static void OpenSourceFile(string fullPath)
        {
            if (!string.IsNullOrEmpty(fullPath) && File.Exists(fullPath))
            {
                try
                {
                    var name = Path.GetFileName(fullPath);

                    var doc = new Document(name, fullPath);
                    AddDocument(doc, ApplicationManager.MainForm.DockPanel);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        ex.Message,
                        Translator.GetStringAndTranslate("strError"), MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation);
                }
            }
            else
            {
                // TODO: Throw exception (?)
                Logger.LogDebugMessage("The file string is null or empty or the file does not exist.");
            }
        }

        /// <summary>
        /// Opens an existing PureBasic source file (using OpenFileDialog)
        /// </summary>
        public static void OpenSourceFile()
        {
            using (var openFileDialog = new OpenFileDialog
            {
                Title = Translator.GetStringAndTranslate("strFileDialogLoadTitle"),
                Filter = Translator.GetStringAndTranslate("strPBSourceFileType") + "|*.pb; *.pbi"
            })
            {
                // Show a new openFileDialog
                if ((openFileDialog.ShowDialog() == DialogResult.Cancel) || ((openFileDialog.FileName == ""))) return;

                OpenSourceFile(openFileDialog.FileName);
            }
        }

        /// <summary>
        /// Saves the current PureBasic source file
        /// </summary>
        public static void SaveCurrentSourceFile()
        {
            try
            {
                var currentDocument = ApplicationManager.MainForm.DockPanel.ActiveDocument as DockContent;
                if (currentDocument is EditorForm) ((EditorForm)currentDocument).SaveThisDocument();
            }
            catch (Exception ex)
            {
                // An error occurred... Let's tell it to the user!
                MessageBox.Show(Translator.GetStringAndTranslate("strErrorOccurredWhileSaving") + '"' + ex.Message + '"');
                Logger.SendException(ex);
            }
        }

        /// <summary>
        /// Saves all files
        /// </summary>
        public static void SaveAllFiles()
        {
            {
                foreach (EditorForm currentDocument in ApplicationManager.MainForm.DockPanel.Documents)
                {
                    try
                    {
                        currentDocument.SaveThisDocument();
                    }
                    catch (Exception ex)
                    {
                        // An error occurred... Let's tell it to the user!
                        MessageBox.Show(Translator.GetStringAndTranslate("strErrorOccurredWhileSaving") + '"' + ex.Message + '"');
                        Logger.SendException(ex);

                    }
                }
            }
        }

        /// <summary>
        /// Adds the specified Document
        /// </summary>
        /// <param name="document">The Document to add</param>
        /// <param name="dockPanel">The DockPanel in what its editor has to be shown</param>
        public static void AddDocument(Document document, DockPanel dockPanel)
        {
            if (document == null) throw new ArgumentNullException();
            if (_documentsDictionary == null) _documentsDictionary = new Dictionary<string, Document>();
            if (_documentsDictionary.ContainsKey(document.Name)) throw new DocumentAlreadyExistsException(document.Name);
            
            _documentsDictionary.Add(document.Name, document);
            // This shows the document on the specified DockPanel
            ShowDocument(document, dockPanel);
        }

        /// <summary>
        /// Removes the specified Document
        /// </summary>
        /// <param name="document">The Document to remove</param>
        /// <returns></returns>
        public static bool RemoveDocument(Document document)
        {
            if (_documentsDictionary != null)
            {
                if (document == null) throw new ArgumentNullException();

                if (_documentsDictionary.ContainsKey(document.Name))
                {
                    document.Editor.Close();

                    _documentsDictionary.Remove(document.Name);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Removes the specified Document
        /// </summary>
        /// <param name="document">The Document to remove</param>
        /// <param name="close">Indicates whether the Document's editor is closed</param>
        /// <returns></returns>
        public static bool RemoveDocument(Document document, bool close)
        {
            if (_documentsDictionary != null)
            {
                if (document == null) throw new ArgumentNullException();

                if (_documentsDictionary.ContainsKey(document.Name))
                {
                    if (close) document.Editor.Close();

                    _documentsDictionary.Remove(document.Name);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Removes the Document with the specified name
        /// </summary>
        /// <param name="name">The name of the Document to remove</param>
        /// <returns></returns>
        public static bool RemoveDocument(string name)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException();

            if (_documentsDictionary != null)
            {
                if (_documentsDictionary.ContainsKey(name))
                {
                    Document doc;

                    if (_documentsDictionary.TryGetValue(name, out doc))
                    {
                        // Close the document editor first
                        doc.Editor.Close();

                        _documentsDictionary.Remove(name);
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Removes the Document with the specified name
        /// </summary>
        /// <param name="name">The name of the Document to remove</param>
        /// <param name="close">Indicates whether the Document's editor is closed</param>
        /// <returns></returns>
        public static bool RemoveDocument(string name, bool close)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException();

            if (_documentsDictionary != null)
            {
                if (_documentsDictionary.ContainsKey(name))
                {
                    Document doc;

                    if (_documentsDictionary.TryGetValue(name, out doc))
                    {
                        // Close the document editor first
                        if (close) doc.Editor.Close();

                        _documentsDictionary.Remove(name);
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Shows the specified Document
        /// </summary>
        /// <param name="document">The Document to show</param>
        /// <param name="dockPanel">The DockPanel in what its editor has to be shown</param>
        /// <returns></returns>
        private static void ShowDocument(Document document, DockPanel dockPanel)
        {
            document.Editor.DockPanel = dockPanel;
            document.Editor.Show();
        }

        /// <summary>
        /// Gets the Document by its name. Returns null, if the the internal Dictionary is not instanced or the document cannot be found.
        /// </summary>
        /// <param name="name">The name of the Document to get</param>
        /// <returns></returns>
        public static Document GetDocument(string name)
        {
            if (_documentsDictionary != null)
            {
                Document doc;
                if (_documentsDictionary.TryGetValue(name, out doc))
                {
                    return doc;
                }
            }
            return null;
        }
    }

    /// <summary>
    /// This class implements the handling of documents
    /// </summary>
    public class Document : ICloneable
    {
        private readonly EditorForm _editor;
        private string _name;

        /// <summary>
        /// Instances a new Document without a file binding
        /// </summary>
        /// <param name="name">The name of the Document</param>
        public Document(string name)
        {
            if (name == null)   throw new ArgumentNullException("name");
            
            _name = name;
            Path = "";
            _editor = new EditorForm(this);
            // TODO: Make new document based on template
        }

        /// <summary>
        /// Instances a new Document with a file binding
        /// </summary>
        /// <param name="name">The name of the Document</param>
        /// <param name="path">The path to the file of the Document</param>
        public Document(string name, string path)
        {
            if (name == null)   throw new ArgumentNullException("name");
            if (path == null)   throw new ArgumentNullException("path");

            _name = name;
            Path = path;
            _editor = new EditorForm(this);

            if (!File.Exists(path)) return;
            _editor.Scintilla.Text = File.ReadAllText(path, Encoding.Default);
            _editor.Scintilla.Modified = false;
        }

        /// <summary>
        /// Gets the formEditor assigned to this Document
        /// </summary>
        public EditorForm Editor
        {
            get
            {
                return _editor;
            }
        }

        /// <summary>
        /// Gets or sets the name of this Document
        /// </summary>
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                if (value == null) throw new ArgumentNullException();

                _name = value;
            }
        }

        /// <summary>
        /// Gets or sets the path to the file of this Document
        /// </summary>
        public string Path { get; set; }

        public string Text
        {
            get
            {
                return _editor.Scintilla.Text;
            }

            set
            {
                if (value == null) throw new ArgumentNullException();
                _editor.Scintilla.Text = value;
            }
        }

        #region ICloneable Member

        public object Clone()
        {
            return MemberwiseClone();
        }

        #endregion
    }
}